package cn.finyzq.ss.games.service.impl;

import cn.finyzq.ss.games.service.WXConnector;
import cn.finyzq.ss.games.utils.HttpUtils;
import cn.finyzq.ss.games.vo.WechatToken;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * Create Time: 2018年02月27日 16:30
 *
 * @author fin
 */
@Service
public class WXConnectorImpl implements WXConnector {


    @Value("${wx.appid}")
    private String appid;

    @Value("${wx.appSecret}")
    private String appSecret;

    @Value("${wx.codeToOpenidUrl}")
    private String codeToOpenidUrl;


    private Logger logger = LoggerFactory.getLogger(WXConnector.class);

    private static final int STUDENT = 0;

    /**
     * 获得学生端openid
     * @param code 用户登录凭证
     * @return 学生微信登录令牌
     */
    @Override
    public WechatToken getWechatTokenByCode(String code) {
        return getTokenFromWechat(appid,appSecret, code);
    }


    private WechatToken getTokenFromWechat(String id,String secret,String code){
        logger.info("get code to openid url");
        String url = codeToOpenidUrl
                .replace("APPID", id)
                .replace("SECRET", secret)
                .replace("JSCODE", code);
//        String ret = HttpUtils.getRestTemplate().getForObject(url, String.class);
        String ret = HttpUtils.getRestTemplate().getForObject(url, String.class);
        logger.info("get ret", ret);
        return JSON.parseObject(ret, WechatToken.class);
    }

    private String getAccessToken(int platform){
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

        url = url.replace("APPID",
                appid).replace("APPSECRET",
                appSecret);

        RestTemplate template = HttpUtils.getRestTemplate();
        return template.getForObject(url, JSONObject.class).getString("access_token");
    }

}
